<template>
    <div class="warehouse-log-container">
        <!-- 新增搜索框 -->
        <div class="search-box" @mouseenter="isExpanded = true" @mouseleave="isExpanded = false">
            <el-input
                v-model="searchKeyword"
                placeholder="输入关键字搜索"
                clearable
                @keyup.enter="searchByKeyword"
                @clear="calculatePageSize"
                :style="{ width: isExpanded ? '200px' : '40px' }"
            >
                <template #prefix>
                    <el-icon><Search /></el-icon>
                </template>
            </el-input>
        </div>
        <ul class="warehouse-log-list" :style="{ height: listHeight + 'px' }">
            <transition-group name="fade">
                <!-- 使用 warehouseId、productId 和 createdAt 字符串组合成唯一 key -->
                <li v-for="(log, index) in warehouseLogData" :key="index" class="warehouse-log-item">
                    <div class="log-item-top">
                        <span :class="`log-type-tag log-type-${log.type}`">{{ log.type }}</span>
                        <!-- 直接显示字符串类型的时间 -->
                        <span class="log-time">{{ dayjs(log.createdAt).format('YYYY-MM-DD HH:mm:ss') }}</span>
                    </div>
                    <div class="log-item-content">
                        <div class="log-info">
                            <span class="log-label">产品名称:</span>
                            <span class="log-value">{{ log.productName }}</span>
                        </div>
                        <div class="log-info">
                            <span class="log-label">变更前数量:</span>
                            <span class="log-value">{{ log.beforeQuantity }}</span>
                        </div>
                        <div class="log-info">
                            <span class="log-label">变更数量:</span>
                            <span class="log-value">{{ log.quantity }}</span>
                        </div>
                        <div class="log-info">
                            <span class="log-label">变更后数量:</span>
                            <span class="log-value">{{ calcQuantity(log) }}</span>
                        </div>
                    </div>
                </li>
            </transition-group>
        </ul>
        <el-pagination
            ref="paginationRef"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="prev, pager, next, jumper, total"
            :total="total"
            class="pagination"
            @current-change="getWarehouseLogEvent"
        />
    </div>
</template>

<script setup lang="ts">
import { getWarehouseLog, searchWarehouseLog } from '@/api/warehouseLog';
import dayjs from 'dayjs';
import { Search } from '@element-plus/icons-vue';
import { ElPagination } from 'element-plus';
import { useSystemStore } from '@/store/modules/system';

onMounted(async () => {
    // 初始化时获取仓库日志数据
    calculatePageSize();
    window.addEventListener('resize', throttledGetWarehouseLogEvent);
});

onUnmounted(() => {
    window.removeEventListener('resize', throttledGetWarehouseLogEvent);
});

/* ***********************************通用属性*********************************** */
// 分页控件引用
const paginationRef = ref<InstanceType<typeof ElPagination>>();
// 当前页码
const currentPage = ref(1);
// 分页大小
const pageSize = ref(10);
// 固定每个列表项的高度为 120px，可根据实际情况调整
const ITEM_HEIGHT = 120;
// 每个列表项的间距
const ITEM_MARGIN = 12;
// 仓库日志总数
const total = ref(0);
// 仓库日志数据
const warehouseLogData = reactive<AjaxResponse['warehouseLogList']>([]);
// 列表高度
const listHeight = ref(0);
// 计算变更后数量
const calcQuantity = (log: AjaxResponse['warehouseLogList'][0]) => {
    let q: string | number = '';
    switch (log.type) {
        case '撤销出库':
            q = log.beforeQuantity + log.quantity;
            break;
        case '生产入库':
            q = log.beforeQuantity + log.quantity;
            break;
        case '盘亏出库':
            q = log.beforeQuantity - log.quantity;
            break;
        case '盘盈入库':
            q = log.beforeQuantity + log.quantity;
            break;
        case '调拨入库':
            q = log.beforeQuantity + log.quantity;
            break;
        case '调拨出库':
            q = log.beforeQuantity - log.quantity;
            break;
        case '调整库存':
            q = log.quantity;
            break;
        case '退货入库':
            q = log.beforeQuantity + log.quantity;
            break;
        case '销售出库':
            q = log.beforeQuantity - log.quantity;
            break;
        default:
            q = '无法计算';
            break;
    }
    return q;
};

/* ***********************************核心更新属性/方法*********************************** */
// 搜索关键字
const searchKeyword = ref('');
// 搜索框展开状态
const isExpanded = ref(false);
// 搜索关键字
const searchByKeyword = async () => {
    if (!searchKeyword.value) {
        ElMessage.warning('请输入关键字');
        return;
    }
    // 重置当前页码为 1
    currentPage.value = 1;
    // 清空仓库日志数据
    warehouseLogData.splice(0, warehouseLogData.length);
    const result = await searchWarehouseLog(currentPage.value, pageSize.value, searchKeyword.value);
    if (result.code === 200) {
        // 仓库日志总数
        total.value = result.total;
        result.data.forEach((item) => {
            warehouseLogData.push(item);
        });
        ElMessage.success('搜索成功');
    }
};

/* ***********************************核心更新属性/方法*********************************** */
// 计算 pageSize 并更新 warehouseLogData
const calculatePageSize = async () => {
    const container = document.querySelector('.warehouse-log-container');
    if (container) {
        // 减去分页器的高度
        const availableHeight = container.clientHeight - 60;
        pageSize.value = Math.floor(availableHeight / (ITEM_HEIGHT + ITEM_MARGIN));
        // 确保 pageSize 至少为 1
        pageSize.value = Math.max(1, pageSize.value);
        listHeight.value = availableHeight;

        await getWarehouseLogEvent();
    } else {
        // 如果容器不存在，确保渲染一次
        await getWarehouseLogEvent();
    }
};
// 更新仓库日志数据事件
const getWarehouseLogEvent = async () => {
    try {
        // 获取仓库日志列表
        const { data, total: count } = await getWarehouseLog(currentPage.value, pageSize.value);
        // 清空旧数据
        warehouseLogData.splice(0, warehouseLogData.length);
        // 仓库日志总数
        total.value = count;
        data.forEach((item) => {
            warehouseLogData.push(item);
        });
    } catch (error) {
        ElMessage.error('获取仓库日志数据失败');
    }
};

// 手动创建一个节流函数
function throttle(func, delay) {
    // 定义一个变量，用于存储定时器 ID
    let timer: any = null;
    // 定义一个变量，用于记录上一次执行回调函数的时间
    let date = 0;
    // 返回一个函数，用于执行节流操作
    return function (...args) {
        // 当前的时间戳
        const now = Date.now();
        // 剩余时间（可能大于0，也可能小于0）
        const remain = delay - (now - date);
        if (remain <= 0) {
            // 如果剩余时间小于等于0，立即执行函数
            if (timer) {
                // 执行函数前先清除定时器
                clearTimeout(timer);
                timer = null;
            }
            // 执行函数
            // @ts-ignore
            func.apply(this, args);
            date = now;
        } else if (!timer) {
            // 如果剩余时间大于0，并且没有定时器，创建一个定时器
            timer = setTimeout(() => {
                // @ts-ignore
                func.apply(this, args);
                date = Date.now();
                timer = null;
            }, remain);
        }

        // 如果剩余时间大于0，且有定时器，则不执行函数 -- 实现节流
    };
}
// 创建节流函数，避免频繁调用 getWarehouseLogEvent
const throttledGetWarehouseLogEvent = throttle(calculatePageSize, 1000);

// 系统配置
const useSystem = useSystemStore();
// 计算宽度
const warehouseLogWidth = computed(() => {
    return useSystem.config.isCollapse ? 'calc(100vw - 84px)' : 'calc(100vw - 220px)';
});
</script>

<style lang="scss" scoped>
// 定义一些颜色变量，方便统一管理和修改
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;
$card-bg: #ffffff; // 卡片白色背景
$border-color: #dcdfe6; // 边框颜色
$text-color: #498bee; // 深灰色文字，增强对比度
$label-color: #666666; // 标签文字颜色
$shadow-color: rgba(0, 0, 0, 0.1); // 阴影颜色

.warehouse-log-container {
    width: v-bind(warehouseLogWidth);
    height: calc(100vh - 80px);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}

// 搜索框样式
.search-box {
    position: fixed;
    right: 10px;
    top: 60px;
    transition: width 0.3s ease;
    z-index: 1000;
    opacity: 0.7;

    // 添加背景色、边框和阴影
    border: 2px solid #4865e9;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .el-input {
        transition: width 0.3s ease;
        overflow: hidden;
    }

    .el-input__prefix {
        cursor: pointer;
    }

    // 鼠标悬停时改变边框颜色
    &:hover {
        border-color: #409eff;
    }
}

.warehouse-log-list {
    list-style: none;
    padding: 10px 0 0 0;
    margin: 0;
    flex: 1;
    overflow-y: auto;
    // 自定义滚动条样式
    &::-webkit-scrollbar {
        width: 6px;
    }
    &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
    }
}

.warehouse-log-item {
    background-color: $card-bg;
    border: 1px solid $border-color;
    padding: 4px;
    margin-bottom: 12px;
    border-radius: 8px;
    transition: all 0.3s ease;
    height: 120px; // 固定高度为 120px
    box-sizing: border-box; // 确保 padding 和 border 包含在高度内

    &:hover {
        box-shadow: 0 4px 12px $shadow-color;
        transform: translateY(-2px);
        border-color: $primary-color;
    }
}

.log-item-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.log-type-tag {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
}

// 不同操作类型的颜色区分和样式
.log-type-生产入库 {
    background-color: rgba($success-color, 0.1);
    color: $success-color;
}

.log-type-销售出库 {
    background-color: rgba($danger-color, 0.1);
    color: $danger-color;
}

.log-type-调整库存 {
    background-color: rgba($warning-color, 0.1);
    color: $warning-color;
}

.log-type-撤销出库 {
    background-color: rgba($info-color, 0.1);
    color: $info-color;
}

.log-type-退货入库 {
    background-color: rgba(92, 184, 122, 0.1);
    color: #5cb87a;
}

.log-type-调拨入库 {
    background-color: rgba(25, 137, 250, 0.1);
    color: #1989fa;
}

.log-type-调拨出库 {
    background-color: rgba(255, 153, 0, 0.1);
    color: #ff9900;
}

.log-type-盘盈入库 {
    background-color: rgba(111, 122, 211, 0.1);
    color: #6f7ad3;
}

.log-type-盘亏出库 {
    background-color: rgba(221, 97, 97, 0.1);
    color: #dd6161;
}

.log-time {
    color: $label-color;
    font-size: 12px;
}

.log-item-content {
    display: grid;
    // 第一个列宽度为2倍，其余列自动填充
    grid-template-columns: 2fr auto;
    // 不换行
    grid-auto-flow: column;
    gap: 4px;
}

.log-info {
    display: flex;
    align-items: center;

    .log-label {
        font-weight: bold;
        color: $label-color;
        width: 100px;
    }

    .log-value {
        color: $text-color;
    }
}

.pagination {
    margin-top: 20px;
    align-self: flex-end;
}

// 过渡动画
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>
